package cn.yunhe.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import cn.yunhe.model.Admin;
import cn.yunhe.model.Cate;
import cn.yunhe.model.News;

public class NewsDaoImpl implements INewsDao {
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;

	public int addNews(News news) {	
		String sql="insert into t_news values(seq_news_news.nextval,?,?,sysdate,?,?,?)";
		Object[] params={news.getTitle(),news.getContent(),news.getCate().getCateId(),
				news.getAdmin().getAdminId(),news.getPic()};
		
		
		return BaseDB.executeUpdate(sql, params);
	}

	
	public List<News> getAllNews() {
		List<News> list= new ArrayList<>();
		conn=BaseDB.getConnection();
		try {
			String sql="select n.nid,n.title,n.writedate,a.adminname,c.cname from t_news n ,t_admin a,t_cate c where"
					+ " n.aid=a.aid and n.cid=c.cid";
			
			pstmt=conn.prepareStatement(sql);
			
			rs=pstmt.executeQuery();
			
			while(rs.next()){
				News news=new News();
				news.setNewsId(rs.getInt("nid"));
				news.setTitle(rs.getString("title"));
				news.setWriteDate(rs.getDate("writedate"));
				
				Admin admin=new Admin();
				admin.setAdminName(rs.getString("adminname"));
				Cate cate = new Cate();
				cate.setCateName(rs.getString("cname"));
				
				news.setAdmin(admin);
				news.setCate(cate);
				
				list.add(news);
				
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		return list;
	}


	
	public News getNewsById(int nid) {
		News news=null;
		conn=BaseDB.getConnection();
		
		try {
			String sql="select n.nid,n.title,n.content,n.writedate,n.pic,a.adminname,c.cname from t_news n ,t_admin a,t_cate c where"
					+ " n.aid=a.aid and n.cid=c.cid and n.nid=?";
			
			pstmt=conn.prepareStatement(sql);
			pstmt.setInt(1, nid);
			
			rs=pstmt.executeQuery();
			
			if(rs.next()){
				news=new News();
				news.setNewsId(rs.getInt("nid"));
				news.setTitle(rs.getString("title"));
				news.setContent(rs.getString("content"));
				news.setWriteDate(rs.getDate("writedate"));
				news.setPic(rs.getString("pic"));
				
				Admin admin=new Admin();
				admin.setAdminName(rs.getString("adminname"));
				Cate cate = new Cate();
				cate.setCateName(rs.getString("cname"));
				
				news.setAdmin(admin);
				news.setCate(cate);
				
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return news;
	}

}
